package io.renren.modules.lucky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.lucky.dao.AppUserScoreDao;
import io.renren.modules.lucky.entity.AppUserScoreEntity;
import io.renren.modules.lucky.service.AppUserScoreService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service("appUserScoreService")
public class AppUserScoreServiceImpl extends ServiceImpl<AppUserScoreDao, AppUserScoreEntity> implements AppUserScoreService {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String userId = (String) params.get("userId");
        IPage<AppUserScoreEntity> page = this.page(
                new Query<AppUserScoreEntity>().getPage(params),
                new QueryWrapper<AppUserScoreEntity>().like(StringUtils.isNotBlank(userId), "user_id", userId)
        );
        return new PageUtils(page);
    }

    @Override
    public List<AppUserScoreEntity> queryPageForApp(Integer pageIndex, Integer pageSize, String userToken, String userId) {
        String id = jwtUtils.getClaimByToken(userToken).getSubject();
        if (userId.equals(id)) {
            //获取积分流水
            QueryWrapper<AppUserScoreEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("score_flag", 1);
            queryWrapper.orderByDesc("id");
            queryWrapper.last("limit " + (pageIndex > 0 ? pageIndex - 1 : pageIndex) * pageSize + ", " + (pageIndex == 0 ? pageSize :  pageIndex * pageSize));
            List<AppUserScoreEntity> list = baseMapper.selectList(queryWrapper);
            return list;
        } else {
            throw new RRException("请求用户id与token不匹配");
        }
    }

}